package com.breadenglish.cms.api.app.sys.servlet;

import com.breadenglish.cms.api.app.common.utils.JacksonObjectMapper;
import com.breadenglish.cms.api.app.common.utils.PropertyConfigurerUtils;
import com.breadenglish.cms.api.app.common.utils.StringUtils;
import com.breadenglish.cms.api.app.dao.FileDao;
import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.sys.service.CodeService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 作者: guo yao
 * 日期: 2015年12月31日
 * 时间: 下午10:31
 */
public class VideoServlet extends HttpServlet {

    private final static Logger logger = LoggerFactory.getLogger(VideoServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filePath = PropertyConfigurerUtils.getProperty(Constants.FILE_PATH);
//        String filePath = PropertyConfigurerUtils.getProperty(Constants.FILE_PATH);
        if (filePath.equals("/upload")) {
            filePath = request.getRealPath(filePath);
        }
//        savePath = savePath + "/uploads/";
        File f1 = new File(filePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        logger.info("uploadify 上传文件开始 ...");
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.info("SharefileUploadServlet Exception" + ex);
            response.setStatus(404);
        }
        String fileName = ""; // 文件名
        String extName = ""; // 后缀名
        String realUrl = ""; // 真实地址
        String src = "";
        String randomName = "";
        Double size = 0D;
        Long fileId = -1L;
        for (FileItem item : fileList) {
            if (!item.isFormField()) {
                fileName = item.getName();
                size = Double.valueOf(item.getSize());
                String type = item.getContentType();
                logger.info("文件大小是：" + size + " 类型是：" + type);
                if (StringUtils.isBlank(fileName)) {
                    logger.info("ProcessRequest fileName is null ");
                    continue;
                }
                //扩展名格式：
                if (fileName.lastIndexOf(".") >= 0) {
                    extName = fileName.substring(fileName.lastIndexOf("."));
                }
                Random random = new Random();
                randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + extName;
                SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
                filePath = filePath + "/" + formater.format(new Date());
                File saveFile = new File(filePath + File.separator + randomName + extName);
//                src = PropertyConfigurerUtils.getProperty(Constants.FILE_PATH) + File.separator  + formater.format(new Date()) + File.separator  + randomName;
//                src = PropertyConfigurerUtils.getProperty(Constants.FILE_PATH) + "/"  + formater.format(new Date()) + "/"  + randomName;
                src = PropertyConfigurerUtils.getProperty(Constants.FILE_SHOW_URL) + formater.format(new Date()) + "/"  + randomName;
                logger.info("文件保存路径是：" + src);
                FileUtils.copyInputStreamToFile(item.getInputStream(), new File(filePath + File.separator  + randomName));
                realUrl = filePath + "/" + randomName;
                try {
                    // 保存文件表
                    ServletContext servletContext = this.getServletContext();
                    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
                    FileDao fileDao = (FileDao) ctx.getBean("fileDao");
                    com.breadenglish.cms.api.app.domain.db.File file = new com.breadenglish.cms.api.app.domain.db.File();
                    fileId = fileDao.getFileId();
                    file.setFileId(fileId);
                    file.setFileType(Constants.FILE_TYPE_DEFAULT);
                    file.setFileClass(Constants.FILE_CLASS_DEFAULT);
                    file.setState(Constants.FILE_CLASS_STATE_TEMP);
                    file.setFileUrl(src);
                    file.setFileName(fileName);
                    file.setSize(size);
                    file.setExt(extName);
                    file.setDelTag(Constants.NOT);
                    file.setCreateTime(new Date());
                    fileDao.insert(file);
                } catch (Throwable e) {
                    e.printStackTrace();
                    if (saveFile.exists()) {
                        saveFile.delete();
                    }
                    response.setStatus(404);
                }
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
//        StringBuffer sb = new StringBuffer();
        // 重命名文件名 [回传文件]
//        sb.append("{src:'").append(src).append("',name:'").append(fileName).append("',realName:'").append(randomName).append("',realUrl:'").append(realUrl);
//        sb.append("',ext:'").append(extName).append("',fileId:'").append(fileId).append("'}");
        result.put("src", src);
        result.put("name", fileName);
        result.put("realName", randomName);
        result.put("realUrl", realUrl);
        result.put("ext", extName);
        result.put("fileId", fileId);
        String resultStr = JacksonObjectMapper.getInstance().writeValueAsString(result);
        response.setContentType("text/html;charset=UTF-8"); // 防止中文乱码
        response.getWriter().print(resultStr);
    }

}
